 //
//  VolunteerInputViewController.m
//  MemberProject
//
//  Created by mac on 15/4/27.
//  Copyright (c) 2015年 MAC OS X. All rights reserved.
//

#import "VolunteerInputViewController.h"
#import "ChoiceDateView.h"
#import "SignInfoViewController.h"
#import "IQKeyboardManager.h"

static CGFloat totalHeight = 200;

@interface VolunteerInputViewController ()
//{
//    NSString *beginDateStr;
//    NSString *endDateStr;
//    AFHTTPRequestOperation *workingOperation;
//}
@property (strong,nonatomic)ChoiceDateView *dateView;

@property (nonatomic,copy) NSString *groupCode;
@property (nonatomic,copy) NSString *groupName;
@property (nonatomic,copy) NSString *activityName;
@property (nonatomic,copy) NSString *activityCode;//活动代号
@property (nonatomic,copy) NSString *locationStr;

@property (nonatomic,copy) NSString *beginDateStr;
@property (nonatomic,copy) NSString *endDateStr;


@end

@implementation VolunteerInputViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"补登记录";
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self setupGroupView];
    
    [self setupView];
//    [self setupFontSize];
    
    [self setupNotification];
//    totalHeight = 200;
}
-(void)setupGroupView
{
    self.activityTextView.delegate=self;
    self.activityTextView.textAlignment=NSTextAlignmentLeft;
    self.activityTextView.isScrollable = NO;
    self.activityTextView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
    self.activityTextView.minNumberOfLines = 1;
    self.activityTextView.maxNumberOfLines = 2;
    self.activityTextView.returnKeyType = UIReturnKeyGo; //just as an example
    self.activityTextView.font = [UIFont systemFontOfSize:15.0f];
    self.activityTextView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);
    self.activityTextView.placeholder = @"请填入活动名称";
    self.activityTextView.textColor = [UIColor colorWithRed:77.0f/255.0f green:208.0f/255.0f blue:200.0f/255.0f alpha:1];

    
    
    
    self.addressTextView.delegate=self;
    self.addressTextView.textAlignment=NSTextAlignmentLeft;
    self.addressTextView.isScrollable = NO;
    self.addressTextView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
    self.addressTextView.minNumberOfLines = 1;
    self.addressTextView.maxNumberOfLines = 2;
    self.addressTextView.returnKeyType = UIReturnKeyGo; //just as an example
    self.addressTextView.font = [UIFont systemFontOfSize:15.0f];
    self.addressTextView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);
    self.addressTextView.placeholder = @"请填入活动地址";
    self.addressTextView.textColor = [UIColor colorWithRed:77.0f/255.0f green:208.0f/255.0f blue:200.0f/255.0f alpha:1];
}

-(void)setupNotification
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addGroupInfo:) name:NotificationPopGroupInfo object:nil];
}
-(void)addGroupInfo:(NSNotification *)sender
{
    NSDictionary *dic = sender.userInfo;
    self.unitLabel.text = dic[@"groupName"];
    CGFloat height = [Utils heightForLabel:self.unitLabel.text andFont:15 andWidth:SCREEN_WIDTH-70];
    self.groupViewHeight.constant = 43+height-20;
    self.totalViewHeight.constant = 200+height-20+self.activityViewHeight.constant-41+self.addressViewHeight.constant-43;
    self.groupName = dic[@"groupName"];
    self.groupCode = dic[@"groupCode"];
    [self.GroupBtn setTitle:@"" forState:0];
}

-(void)setupFontSize
{
    if (iPhone6||iPhone6Plus) {
        for (UIView *view in self.view.subviews) {
            for (int i=101; i<105; i++) {
                UIView *superView = [view viewWithTag:i];
                for (UIView *tView in superView.subviews) {
                    if ([tView isKindOfClass:[UIButton class]]) {
                        UIButton *btn = (UIButton *)tView;
                        btn.titleLabel.font = [UIFont systemFontOfSize:13];
                    }else if ([tView isKindOfClass:[UILabel class]])
                    {
                        UILabel *label = (UILabel *)tView;
                        label.font =[UIFont systemFontOfSize:13];
                    }else if ([tView isKindOfClass:[UITextField class]])
                    {
                        UITextField *field = (UITextField *)tView;
                        field.font = [UIFont systemFontOfSize:13];
                    }else if ([tView isKindOfClass:[UITextView class]])
                    {
                        UITextView *textView = (UITextView *)tView;
                        textView.font = [UIFont systemFontOfSize:13];
                    }
                }
                
            }
            
            
            
        }
    }
    
}
-(void)setupView
{
//    [self.UnitBtn addTarget:self action:@selector(addUnit:) forControlEvents:64];
    
    [self.beginDateBtn addTarget:self action:@selector(addDate:) forControlEvents:64];
    [self.endDateBtn addTarget:self action:@selector(addDate:) forControlEvents:64];
    
//    [self.addressBtn addTarget:self action:@selector(choiceAddress:) forControlEvents:64];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelEdit)];
    [self.view addGestureRecognizer:tap];
    

    
    //是否需要自己填入活动信息
    if (self.isAlreadyInputActiveCode) {
        
        [self setValueByDic];
        
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"yyyyMMdd HHmmss"];
        
        NSDateFormatter *format = [[NSDateFormatter alloc]init];
        [format setDateFormat:@"yyyy-MM-dd HH:mm"];
        
        NSDate *beginDate = [dateFormatter dateFromString:self.beginDateStr];
        NSDate *endDate = [dateFormatter dateFromString:self.endDateStr];
        
        
        
        
        self.GroupBtn.hidden = YES;
        self.unitLabel.text = self.groupName;
        CGFloat height = [Utils heightForLabel:self.unitLabel.text andFont:15 andWidth:SCREEN_WIDTH-70];
        self.groupViewHeight.constant = 43+height-20;
        self.totalViewHeight.constant = 200+height-20+self.activityViewHeight.constant-41+self.addressViewHeight.constant-43;
        
    
        [self.beginDateBtn setTitle:[format stringFromDate:beginDate] forState:0];
        self.beginDateBtn.selected = YES;
        
        
        [self.endDateBtn setTitle:[format stringFromDate:endDate] forState:0];
        self.endDateBtn.selected = YES;
        
        self.addressTextView.text = self.locationStr;
        
        self.activityTextView.text = self.activityName;
        
        [self.addressTextView refreshHeight];
        [self.activityTextView refreshHeight];
        
        
        UIView *inputView = [self.view viewWithTag:2015];
        inputView.userInteractionEnabled = NO;
        
    }else
    {
        
        self.GroupBtn.hidden = NO;
        [self.GroupBtn addTarget:self action:@selector(inputGroupInfo:) forControlEvents:64];
    }
    
}

-(void)setValueByDic
{
    NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithDictionary:self.activityDic];
    for (NSString *key in mDic.allKeys) {
        id object = self.activityDic[key];
        if (object==nil||[object isKindOfClass:[NSNull class]]) {
            [mDic setValue:@"" forKey:key];
        }
    }
    self.groupCode = mDic[@"groupCode"];
    self.groupName = mDic[@"groupName"];
    self.activityCode = mDic[@"activityCode"];
    self.activityName = mDic[@"activityName"];
    self.beginDateStr = mDic[@"activityStartPeriod"];
    self.endDateStr = mDic[@"activityEndPeriod"];
    self.locationStr = mDic[@"activityLocation"];
    
}

-(void)inputGroupInfo:(UIButton *)sender
{
    [self showQz:ActivityGroupStyle];
    [self getZBarPushBlockStr:^(NSString *result) {
        [self getGroupInfo:result];
    }];
    
    
    
}
-(void)getGroupInfo:(NSString *)result
{
    [SVProgressHUD showWithStatus:@"扫描中。。" maskType:SVProgressHUDMaskTypeBlack];
    [[BuaatVolunteerServerSDK sharedInstance]requestQrcodeGroupInfoWithGroupCode:result success:^(NSHTTPURLResponse *response, id responseObject) {
        [SVProgressHUD dismiss];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            id result = responseObject[@"result"];
            if ([result isKindOfClass:[NSDictionary class]]) {
                NSString *groupCode = result[@"groupCode"];
                NSString *groupName = result[@"groupName"];
                self.groupCode = groupCode;
                self.groupName = groupName;
                self.unitLabel.text = self.groupName;
                CGFloat height = [Utils heightForLabel:self.unitLabel.text andFont:15 andWidth:SCREEN_WIDTH-70];
                self.groupViewHeight.constant = 43+height-20;
                self.totalViewHeight.constant = 200+height-20+self.activityViewHeight.constant-41+self.addressViewHeight.constant-43;
                
                [self.GroupBtn setTitle:@"" forState:0];
                
            }else
            {
                [SVProgressHUD showErrorWithStatus:@"没有该机构" maskType:SVProgressHUDMaskTypeBlack];
            }
        }else
        {
            [SVProgressHUD showErrorWithStatus:@"没有该机构" maskType:SVProgressHUDMaskTypeBlack];
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误" maskType:SVProgressHUDMaskTypeBlack];

    }];
}

-(void)cancelEdit
{
    [self.addressTextView resignFirstResponder];
    [self.activityTextView resignFirstResponder];
}
-(void)choiceAddress:(UIButton *)sender
{
    SignInfoViewController *infoVC = [[SignInfoViewController alloc]initWithNibName:@"SignInfoViewController" bundle:nil];
    [infoVC setIsDetailAddress:YES];
    [infoVC setPickViewStyle:PickViewAeraThreeChoice];
    [infoVC finishDateEdit:^(NSString *nameStr) {
        sender.selected = YES;
        [self.addressBtn setTitle:nameStr forState:UIControlStateSelected];
    }];
//    [infoVC finishEdit:^(NSString *str) {
//        sender.selected = YES;
//        [self.addressBtn setTitle:str forState:UIControlStateSelected];
//    }];

    
    [self.navigationController pushViewController:infoVC animated:YES];
}
//-(void)addUnit:(UIButton *)sender
//{
////    [self showQz:MyZbarStyle];
////    [self getZBarPushBlockStr:^(id result) {
////        [SVProgressHUD showInfoWithStatus:result maskType:SVProgressHUDMaskTypeBlack];
////    }];
//    UIAlertView *myAlertView=[[UIAlertView alloc] initWithTitle:@"活动单位号输入" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消",nil];
//    [myAlertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
//    [myAlertView show];
//    
//    
//}
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    UITextField *tField = [alertView textFieldAtIndex:0];
//    tField.keyboardType = UIKeyboardTypeNumberPad;
//    if (buttonIndex==0&&![tField.text isEqualToString:@""]) {
//        [self getUnitInfo:tField.text];
//    }
//    
//}
//#pragma mark 获取单位信息
//-(void)getUnitInfo:(NSString *)UnitId
//{
//    [SVProgressHUD showWithStatus:@"查询中" maskType:SVProgressHUDMaskTypeBlack];
//    NSDictionary *parameters = @{@"token":@"sdfsadfsadfasdf",@"module":@"VoluteerGroup",@"method":@"loadVoluteerGroupBycode",@"requestId":[NSNull new],@"requestParam":@[UnitId]};
//    self.workingOperation = [Utils requestDic:parameters andRusult:^(id result) {
//        if ([result isKindOfClass:[NSDictionary class]]) {
//            
//            NSDictionary *responseData =result[@"responseData"];
//            if(![responseData isKindOfClass:[NSNull class]])
//            {
//                NSDictionary *responseData = result[@"responseData"];
//                [SVProgressHUD dismiss];
//                if (responseData&&responseData.allKeys.count>0) {
//                    NSString *groupName = responseData[@"groupName"];
//                    [self.unitLabel setText:groupName];
//                    [self.unitLabel setTextColor:[UIColor colorWithRed:77.0f/255.0f green:208.0f/255.0f blue:200.0f/255.0f alpha:1]];
//                }
//            }else{
//                [SVProgressHUD showErrorWithStatus:@"没有该机构" maskType:SVProgressHUDMaskTypeBlack];
//                [self.unitLabel setText:@""];
//                
//            }
//            
//            
//        }else
//        {
//            [SVProgressHUD showErrorWithStatus:@"网络错误" maskType:SVProgressHUDMaskTypeBlack];
//            [self.unitLabel setText:@""];
//        }
//    } andError:^(id result) {
//        [SVProgressHUD showErrorWithStatus:@"网络错误" maskType:SVProgressHUDMaskTypeBlack];
//        [self.unitLabel setText:@""];
//        
//    }];
//}
-(void)viewWillAppear:(BOOL)animated
{
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.dateView) {
        [self.dateView backAction];
    }
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}
-(void)addDate:(UIButton *)sender
{

    [self cancelEdit];
//    [self.activityField resignFirstResponder];
    if (!self.dateView) {
        self.dateView=[[[NSBundle mainBundle] loadNibNamed:@"ChoiceDateView" owner:self options:nil]lastObject];
    }
    
    [self.dateView show:self];
    
    if (sender.tag ==21) {
        self.dateView.infoLabel.text = @"活动开始时间";
    }else
        self.dateView.infoLabel.text = @"活动结束时间";
    
    [self.dateView doneActionBlock:^(NSString *submitStr) {
        [self.dateView backAction];
        if (sender.tag ==21) {
            submitStr = [NSString stringWithFormat:@"%@:00",submitStr];
            self.beginDateStr = submitStr;
            
        }else
        {
            submitStr = [NSString stringWithFormat:@"%@:00",submitStr];
            self.endDateStr = submitStr;
        }
        
            sender.selected = YES;
        [sender setTitle:submitStr forState:UIControlStateSelected];
    }];

    
    

}
- (IBAction)subAction:(UIButton *)sender
{
    
    
    
    
    if ([self.unitLabel.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"活动单位组织方不能为空" maskType:SVProgressHUDMaskTypeBlack];
        return;
    }
    if ([self.activityTextView.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"活动名称不能为空" maskType:SVProgressHUDMaskTypeBlack];
        return;
    }
    
    if (!self.beginDateStr) {
        [SVProgressHUD showErrorWithStatus:@"活动开始时间不能为空" maskType:SVProgressHUDMaskTypeBlack];
        return;
    }
    if (!self.endDateStr) {
        [SVProgressHUD showErrorWithStatus:@"活动结束时间不能为空" maskType:SVProgressHUDMaskTypeBlack];
        return;
    }
    NSString *beginStr = @"";
    NSString *endStr = @"";
    
    NSArray *beginArr = [self.beginDateStr componentsSeparatedByCharactersInSet: [NSCharacterSet
                                                                     characterSetWithCharactersInString:@":-"]];
    if (beginArr.count>0) {
        for (int i=0; i<beginArr.count; i++) {
            beginStr = [NSString stringWithFormat:@"%@%@",beginStr,beginArr[i]];
        }
    }else
    {
        beginStr =self.beginDateStr;
    }
    
    
    NSArray *endArr = [self.endDateStr componentsSeparatedByCharactersInSet: [NSCharacterSet
                                                                     characterSetWithCharactersInString:@":-"]];
    if (!self.isAlreadyInputActiveCode) {
        for (int i=0; i<endArr.count; i++) {
            endStr = [NSString stringWithFormat:@"%@%@",endStr,endArr[i]];
        }
    }else
    {
        endStr = self.endDateStr;
    }
    
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    if (self.isAlreadyInputActiveCode) {
        [dateFormatter setDateFormat:@"yyyyMMdd HHmmss"];
    }else
    {
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    }
    NSDate *beginDate = [dateFormatter dateFromString:self.beginDateStr];
    NSDate *endDate = [dateFormatter dateFromString:self.endDateStr];
    NSTimeInterval timebe = [endDate timeIntervalSinceDate:beginDate];
    if (timebe<=0) {
         [SVProgressHUD showErrorWithStatus:@"结束时间不得早于开始时间" maskType:SVProgressHUDMaskTypeBlack];
        return;
    }
    if ([self.addressTextView.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入具体地点" maskType:SVProgressHUDMaskTypeBlack];
        return;
    }
    
    
    [self submitInfomation:beginStr andEndStr:endStr];
    
    
}
#pragma mark 提交信息
-(void)submitInfomation:(NSString *)beginStr andEndStr:(NSString *)endStr
{
    NSString *activeName = self.activityTextView.text;
    NSString *location = self.addressTextView.text;
    NSString *volunteerCode = [UserInfoManager sharedManager].modelMser.volunteerCode;
    
    if (!self.isAlreadyInputActiveCode) {
        self.activityCode = @"";
    }
    //补登提交信息
    [SVProgressHUD showWithStatus:@"正在提交" maskType:SVProgressHUDMaskTypeBlack];
    [[BuaatVolunteerServerSDK sharedInstance]
                                            requestActivityRecord4UnregWithActiveName:activeName
                                            activeStartTime:beginStr
                                            activeEndTime:endStr
                                            location:location
                                            groupCode:self.groupCode
                                            volunteerCode:volunteerCode
                                            activityCode:self.activityCode
    success:^(NSHTTPURLResponse *response, id responseObject) {
        [SVProgressHUD dismiss];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            id ret = responseObject[@"ret"];
            if ([ret isKindOfClass:[NSNumber class]]) {
                NSNumber *num = ret;
                if (num.intValue==0) {
                   //补登成功
                    [SVProgressHUD showSuccessWithStatus:@"补登成功" maskType:SVProgressHUDMaskTypeBlack];
                    if (self.isDismissVC) {
                        dispatch_after(0.2, dispatch_get_main_queue(), ^{
                            
//                            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                            
                            [[NSNotificationCenter defaultCenter]postNotificationName:NSNotificationRefreshTableView object:nil];
                            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                            
                        });
                        
                    }else
                    {
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [self.refreshDelegate refreshTable];
                            [self.navigationController popViewControllerAnimated:YES];
                            
                        });
                    }
                    
                    
                }else
                {
                    [SVProgressHUD showErrorWithStatus:@"补登失败" maskType:SVProgressHUDMaskTypeBlack];
                }
            }else
            {
                [SVProgressHUD showErrorWithStatus:@"补登失败" maskType:SVProgressHUDMaskTypeBlack];
            }

        }else
        {
            [SVProgressHUD showErrorWithStatus:@"补登失败" maskType:SVProgressHUDMaskTypeBlack];
        }
        
        
        
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        
        
        [SVProgressHUD showErrorWithStatus:@"网络错误" maskType:SVProgressHUDMaskTypeBlack];
    }];
    
    
    
        
    
    
    
}

- (void)growingTextView:(HPGrowingTextView *)growingTextView didChangeHeight:(float)height
{
    
    if (growingTextView.tag ==333)
    {
        
        self.activityViewHeight.constant = 41+height-34;
        self.totalViewHeight.constant = 200+height-34+ self.addressViewHeight.constant-43+self.groupViewHeight.constant-43;
        
        
    }
    else if (growingTextView.tag ==334)
    {
        self.addressViewHeight.constant = 43+height-34;
        self.totalViewHeight.constant = 200+height-34+self.activityViewHeight.constant-41+self.groupViewHeight.constant-43;
    }
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (self.dateView) {
        [self.dateView backAction];
    }
    
}
//-(void)textFieldDidEndEditing:(UITextField *)textField
//{
//    if (![textField.text isEqualToString:@""]) {
//        [self getUnitInfo:textField.text];
//    }
//    
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
